package priv.pfz.basedao.mybatis.sqlprovider;

import org.apache.ibatis.builder.annotation.ProviderContext;
import priv.pfz.basedao.Utils;
import priv.pfz.basedao.info.DaoInfo;
import priv.pfz.basedao.mybatis.DaoInfoCache;
import priv.pfz.basedao.query.BaseQuery;
import priv.pfz.basedao.sharding.ShardingInfo;
import priv.pfz.basedao.sharding.ShardingManager;
import priv.pfz.basedao.sqlbuilder.SQL;

/**
 * SELECT count(*) FROM table WHERE query
 * @author yyjxp
 * 2024/1/28 23:55
 */
public class CountSqlProvider extends BaseSqlProvider {

    public String provideSql(BaseQuery<?> query, ProviderContext context) {
        return innerProvideSql(query, null, null, context);
    }

    public String provideShardingSql(BaseQuery<?> query, ShardingInfo shardingInfo, ProviderContext context) {
        return innerProvideSql(query, "arg0", shardingInfo, context);
    }

    private String innerProvideSql(BaseQuery<?> query, String queryArgName, ShardingInfo shardingInfo, ProviderContext context) {
        Utils.checkNotNull(query, "query不能为空");
        query.overrideMyBatisPlaceholder(queryArgName);
        DaoInfo daoInfo = DaoInfoCache.getDaoInfo(context.getMapperType());
        ShardingManager shardingManager = new ShardingManager(daoInfo, shardingInfo);
        shardingManager.addShardingInfos(query);

        SQL sql = new SQL();
        sql.SELECT("count(*)");
        sql.FROM(shardingManager.getShardingTable());
        sql.WHERE(query.getConditionSql());
        if (daoInfo.isEnableLogicDelete()) {
            sql.WHERE(getLogicDeleteWhere(daoInfo));
        }
        String sqlStr = sql.toString();
        sqlStr += shardingManager.getThirdShardingStr();
        System.out.println(sqlStr);
        return sqlStr;
    }
}
